package org.garbagecan.quartzstudy.cron;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class TestMultiCronCalendar {
	public static void main(String[] args) throws Exception {
		test();
	}
	
	public static void test() throws Exception {
		print("\nTestMultiCronCalendar.test: -------------------------------");
		List<String> list = new ArrayList<String>();
		// list.add("0/3 * * ? * * 2007");
		list.add("5,15,25,35,45,55 * * ? * * *");
		list.add("0,10,20,30,40,50 * * ? * * *");
		MultiCronCalendar cc = new MultiCronCalendar(list);
		print("The cron expressions list are :" + list);

		String sDate;
		Date date;

		sDate = "2012-04-05 10:00:00.000";
		date = parseToDate(sDate);
		print(sDate + " isTimeIncluded : " + cc.isTimeIncluded(date.getTime()));

		sDate = "2012-04-05 10:00:00.000";
		date = parseToDate(sDate);
		print(sDate + " isTimeIncluded : " + cc.isTimeIncluded(date.getTime()));

		SchedulerFactory sf = new StdSchedulerFactory();
		Scheduler scheduler = sf.getScheduler();
		
		JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("myjob","mygroup").build();
		
		Trigger trigger = TriggerBuilder.newTrigger()
				.withIdentity("mytrigger", "mygroup")
				.forJob(jobDetail)
				.startNow()
				.withPriority(5)
				.withSchedule(CronScheduleBuilder
					.cronSchedule("* * * ? * * *"))
				.build();

		scheduler.addCalendar("cal", cc, true, true);

		scheduler.scheduleJob(jobDetail, trigger);

		scheduler.start();
		Thread.sleep(100000);
		scheduler.shutdown();
	}

	public static Date parseToDate(String s) throws ParseException {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date date = df.parse(s);
		return date;
	}

	public static void print(Object obj) {
		System.out.print("\t");
		System.out.println(obj);
	}
}
